import React from 'react';
import { connect } from 'dva';
import { Divider, Select, Row, Col } from 'antd';
import _ from 'lodash';
import dimensionStyle from './DataDimensionOpt.less';

const getShowName = item => {
  if (item.source) {
    return `${item.id}-${item.source}`;
  }
  return `${item.id}`;
};
@connect(user => ({ user }))
class SelectUserStep extends React.Component {
  state = {};

  componentDidMount() {
    this.lazyFetch = _.debounce(this.fetchByName, 300);
    const { onParentStateValueChange } = this.props;
    this.onUserListChange = onParentStateValueChange('erpUserList');
    this.onUserIdListChange = onParentStateValueChange('erpUserId');
    this.onSelectUserIdchange = onParentStateValueChange('selectedUserList');
  }

  componentWillReceiveProps(nextProps) {
    const { userIdList: newUserIdList } = nextProps;
    const { userIdList } = this.props;
    if (!this.inited && newUserIdList.length !== userIdList.length) {
      this.fetchByIdList(newUserIdList);
      this.inited = true;
    }
  }

  fetchByName = username => {
    if (username && username.length > 0) {
      this.fetch({ username }, ({ rows }) => {
        this.onUserListChange(rows);
      });
    }
  };

  fetchByIdList = userIdList => {
    if (userIdList && userIdList.length > 0) {
      let isAllZero = false;
      if (userIdList.length === 1) {
        isAllZero = userIdList[0] === '0';
      }
      if (!isAllZero) {
        this.fetch({ erpUserId: userIdList }, ({ rows }) => {
          this.onSelectUserIdchange(rows);
        });
      }
    }
  };

  fetch = (params, callback) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'user/fetchErpUserInfo',
      payload: params,
      callback,
    });
  };

  onValueChangeEvent = value => {
    const { selectedUserList } = this.props;
    let newSelectedUserList = [];
    if (value) {
      const selectedMapper = {};
      value.forEach(item => {
        selectedMapper[item] = true;
      });
      newSelectedUserList = selectedUserList.filter(item => selectedMapper[item.id]);
    }
    this.onUserIdListChange(value);
    this.onSelectUserIdchange(newSelectedUserList);
  };

  getUserList = () => {
    const { erpUserList = [], selectedUserList = [] } = this.props;
    const userIdMapper = {};
    erpUserList.forEach(user => {
      userIdMapper[user.id] = true;
    });
    const tempList = selectedUserList.filter(user => !userIdMapper[user.id]);
    return [{ id: '0', name: '全部' }, ...erpUserList, ...tempList];
  };

  renderContent = () => {
    const { userIdList } = this.props;
    return (
      <div className={dimensionStyle.UserStepContent}>
        <Row>
          <Col offset={4}>
            <div>
              <span style={{ marginRight: '10px' }}>用户关联:</span>
              <Select
                showSearch
                value={userIdList}
                placeholder="请关联用户"
                defaultActiveFirstOption={false}
                showArrow
                mode="multiple"
                filterOption={false}
                onSearch={this.lazyFetch}
                onChange={this.onValueChangeEvent}
                style={{ width: '500px' }}
              >
                {this.getUserList().map(item => (
                  <Select.Option key={getShowName(item)} value={item.id}>
                    {item.name}({getShowName(item)})
                  </Select.Option>
                ))}
              </Select>
            </div>
          </Col>
        </Row>
      </div>
    );
  };

  render() {
    return (
      <div className={dimensionStyle.UserStep}>
        <Divider type="horizontal" />
        {this.renderContent()}
      </div>
    );
  }
}

export default SelectUserStep;
